package com.org.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.org.common.PageBean;
import com.org.common.Result;
import com.org.pojo.CommunityActivity;
import com.org.pojo.CommunityActivityRespon;
import com.org.pojo.ServeRespond;
import com.org.service.ICommunityActivityResponService;
import com.org.service.ICommunityActivityService;
import com.org.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import org.web3j.abi.datatypes.Int;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author cjx
 * @since 2024-03-03
 */
@RestController
@RequestMapping("/community-activity-respon")
public class CommunityActivityResponController {

    @Autowired
    private ICommunityActivityService communityActivityService;

    @Autowired
    private ICommunityActivityResponService communityActivityResponService;

    /**
     * 用户报名社区活动
     * 社区活动有 已发布|进行中|已完成 三个状态
     * 只能报名状态为 已发布 的活动
     * 到了开始时间后活动状态转为 进行中 ；响应状态转为进行中
     * 社区活动不像服务一样需要双方进行验证，到了活动结束时间后自动状态变为 已完成；响应状态转为已完成
     * 传入参数格式
     * {
     * "activityId": 1
     * }
     */
    @PostMapping("/sign")
    public Result signCommunityActivity(@RequestBody Map<String, Object> params) {
        Integer activityId = (Integer) params.get("activityId");
        Map<String, Object> param = ThreadLocalUtil.get();
        Integer userId = (Integer) param.get("id");
        System.out.println(activityId);
        // 社区活动
        CommunityActivity communityActivity = communityActivityService.getById(activityId);
        // 活动剩余人数
        int remaining = communityActivity.getNumPeople() - communityActivity.getNumJoin();
        // 还没开始并且人数没满的服务才能报名
        if (communityActivity.getState().equals("已发布") && remaining > 0) {
            // 报名人数加一并更新活动
            communityActivity.setNumJoin(communityActivity.getNumJoin() + 1);
            communityActivityService.updateById(communityActivity);
            // 先判断表中是否存在了这个响应
            LambdaQueryWrapper<CommunityActivityRespon> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(CommunityActivityRespon::getUserId, userId)
                    .eq(CommunityActivityRespon::getActivityId, activityId);
            CommunityActivityRespon one = communityActivityResponService.getOne(lambdaQueryWrapper);
            if(one != null){
                one.setState("已选择");
                communityActivityResponService.updateById(one);
                return Result.success();
            }
            else {
                // 用户加入活动响应表
                CommunityActivityRespon communityActivityRespon = new CommunityActivityRespon();
                communityActivityRespon.setUserId(userId);
                communityActivityRespon.setActivityId(activityId);
                communityActivityRespon.setState("已选择");
                communityActivityRespon.setCreateTime(LocalDateTime.now());
                communityActivityResponService.save(communityActivityRespon);
                return Result.success();
            }
        } else if (communityActivity.getState().equals("进行中")) {
            return Result.error("该活动已开始，下次快一点哦");
        } else if (communityActivity.getState().equals("已完成")) {
            return Result.error("该活动已结束，下次快一点哦");
        } else {
            return Result.error("活动人数已满，下次快一点哦");
        }
    }

    /**
     * 用户取消报名传入参数格式
     * {
     * "activityId": 1
     * }
     */
    @PostMapping("/cancel")
    public Result cancelCommunityActivity(@RequestBody Map<String, Object> params) {
        int activityId = (int) params.get("activityId");
        Map<String, Object> param = ThreadLocalUtil.get();
        Integer userId = (Integer) param.get("id");
        CommunityActivityRespon communityActivityRespon = communityActivityResponService.getOne(new LambdaQueryWrapper<CommunityActivityRespon>()
                .eq(CommunityActivityRespon::getUserId, userId)
                .eq(CommunityActivityRespon::getActivityId, activityId));
        if (communityActivityRespon != null) {
            // 更新响应为已撤销
            communityActivityRespon.setState("已撤销");
            communityActivityResponService.updateById(communityActivityRespon);
            // 活动人数减一
            CommunityActivity communityActivity = communityActivityService.getById(activityId);
            communityActivity.setNumJoin(communityActivity.getNumJoin() - 1);
            communityActivityService.updateById(communityActivity);
            return Result.success();
        } else {
            return Result.error("您还未报名该活动");
        }
    }

    /**
     * 判断用户参加了某个活动没
     */
    @GetMapping("/isJoin")
    public Result<Boolean> isJoinCommunityActivity(int activityId) {
        Map<String, Object> param = ThreadLocalUtil.get();
        Integer userId = (Integer) param.get("id");
        
        LambdaQueryWrapper<CommunityActivityRespon> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CommunityActivityRespon::getUserId, userId)
                .eq(CommunityActivityRespon::getActivityId, activityId);
        CommunityActivityRespon communityActivityRespon = communityActivityResponService.getOne(lambdaQueryWrapper);
        if (communityActivityRespon != null && communityActivityRespon.getState().equals("已选择")) {
            return Result.success(true);
        } else {
            return Result.success(false);
        }
    }

    // 通过 id 获取详情
    @GetMapping("/detail")
    public Result<CommunityActivityRespon> getCommunityActivityResponseDetail(long id) {
        return Result.success(communityActivityResponService.getById(id));
    }

    // 分页
    @GetMapping("/list")
    public Result<PageBean<CommunityActivityRespon>> getCommunityActivityResponses(
            Integer pageNum,    //第几页
            Integer pageSize,   //页面容量
            Boolean isUp,        //true：按创建时间升序排序，false：按创建时间降降序 不可为空
            String activityId,     //社区id 可为空，可以不传
            String userId         //用户id 可为空，可以传
    ) {

        Page<CommunityActivityRespon> page = new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);

        LambdaQueryWrapper<CommunityActivityRespon> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (activityId != null && !activityId.isEmpty()) {
            lambdaQueryWrapper.eq(CommunityActivityRespon::getActivityId, activityId);
        }
        if (userId != null && !userId.isEmpty()) {
            lambdaQueryWrapper.eq(CommunityActivityRespon::getUserId, userId);
        }
        // isUp 为真，则按时间升序
        lambdaQueryWrapper.orderBy(isUp, true, CommunityActivityRespon::getCreateTime);
        // 否则按时间降序
        lambdaQueryWrapper.orderBy(!isUp, false, CommunityActivityRespon::getCreateTime);
        // 分页
        IPage<CommunityActivityRespon> iPage = communityActivityResponService.page(page, lambdaQueryWrapper);

        PageBean<CommunityActivityRespon> pageBean = new PageBean<>();
        pageBean.setTotal(iPage.getTotal());
        pageBean.setItems(iPage.getRecords());

        return Result.success(pageBean);
    }

    // 更新活动表的状态
    // 在数据库中设置了触发器，不需要在后端代码中另行处理

}
